<template>
    <div class="app-container">
        <el-form :model="queryParams"
                 ref="queryForm"
                 :inline="true"
                 v-show="showSearch"
                 label-width="68px">
            <el-form-item label="模块类型"
                          prop="moduleType">
                <el-select v-model="queryParams.moduleType"
                           placeholder="请选择模块类型"
                           clearable
                           size="small">
                    <el-option v-for="dict in stateOptions"
                               :key="dict.dictValue"
                               :label="dict.dictLabel"
                               :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="图片id"
                          prop="imageId">
                <el-input v-model="queryParams.imageId"
                          placeholder="请输入图片id"
                          clearable
                          size="small"
                          @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="标题"
                          prop="title">
                <el-input v-model="queryParams.title"
                          placeholder="请输入标题"
                          clearable
                          size="small"
                          @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="跳转地址"
                          prop="jumpUrl">
                <el-input v-model="queryParams.jumpUrl"
                          placeholder="请输入跳转地址"
                          clearable
                          size="small"
                          @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="跳转类型"
                          prop="jumpType">
                <el-select v-model="queryParams.jumpType"
                           placeholder="请选择跳转类型"
                           clearable
                           size="small">
                    <el-option label="请选择字典生成"
                               value="" />
                </el-select>
            </el-form-item>
            <el-form-item label="排序"
                          prop="sort">
                <el-input v-model="queryParams.sort"
                          placeholder="请输入排序"
                          clearable
                          size="small"
                          @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="cyan"
                           icon="el-icon-search"
                           size="mini"
                           @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh"
                           size="mini"
                           @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10"
                class="mb8">
            <el-col :span="1.5">
                <el-button type="primary"
                           icon="el-icon-plus"
                           size="mini"
                           @click="handleAdd"
                           v-hasPermi="['operater:moduleResource:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success"
                           icon="el-icon-edit"
                           size="mini"
                           :disabled="single"
                           @click="handleUpdate"
                           v-hasPermi="['operater:moduleResource:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="mini"
                           :disabled="multiple"
                           @click="handleDelete"
                           v-hasPermi="['operater:moduleResource:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning"
                           icon="el-icon-download"
                           size="mini"
                           @click="handleExport"
                           v-hasPermi="['operater:moduleResource:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch"
                           @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading"
                  :data="moduleResourceList"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection"
                             width="55"
                             align="center" />
            <el-table-column label="id"
                             align="center"
                             prop="id" />
            <el-table-column label="模块类型"
                             align="center"
                             prop="moduleType"
                             :formatter="stateFormat" />
            <el-table-column label="图片id"
                             align="center"
                             prop="imageId" />
            <el-table-column label="标题"
                             align="center"
                             prop="title" />
            <el-table-column label="内容(文字)"
                             align="center"
                             prop="content" />
            <el-table-column label="跳转地址"
                             align="center"
                             prop="jumpUrl" />
            <el-table-column label="跳转类型"
                             align="center"
                             prop="jumpType" />
            <el-table-column label="排序"
                             align="center"
                             prop="sort" />
            <el-table-column label="操作"
                             align="center"
                             class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini"
                               type="text"
                               icon="el-icon-edit"
                               @click="handleUpdate(scope.row)"
                               v-hasPermi="['operater:moduleResource:edit']">修改</el-button>
                    <el-button size="mini"
                               type="text"
                               icon="el-icon-delete"
                               @click="handleDelete(scope.row)"
                               v-hasPermi="['operater:moduleResource:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList" />

        <!-- 添加或修改模块资源对话框 -->
        <el-dialog :title="title"
                   :visible.sync="open"
                   width="500px"
                   append-to-body>
            <el-form ref="form"
                     :model="form"
                     :rules="rules"
                     size="medium"
                     label-width="100px">
                <el-form-item label="模块类型"
                              prop="moduleType">
                    <el-select v-model="form.moduleType"
                               placeholder="请选择模块类型"
                               clearable
                               :style="{width: '100%'}">

                        <el-option v-for="dict in stateOptions"
                                   :key="dict.dictValue"
                                   :label="dict.dictLabel"
                                   :value="dict.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="上传"
                              prop="imageId">

                    <el-upload ref="uploadFaceImg"
                               class="avatar-uploader"
                               :action="uploadFaceImgAction"
                               :show-file-list="false"
                               :on-success="handleAvatarSuccess"
                               :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl"
                             :src="imageUrl"
                             class="avatar">
                        <i v-else
                           class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="标题"
                              prop="title">
                    <el-input v-model="form.title"
                              placeholder="请输入标题"
                              clearable
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="跳转地址"
                              prop="jumpUrl">
                    <el-input v-model="form.jumpUrl"
                              placeholder="请输入跳转地址"
                              clearable
                              :style="{width: '100%'}">
                    </el-input>
                </el-form-item>
                <el-form-item label="跳转类型"
                              prop="jumpType">
                    <el-input v-model="form.jumpType"
                              placeholder="请输入跳转类型"
                              clearable
                              :style="{width: '100%'}">
                    </el-input>
                </el-form-item>
                <el-form-item label="排序"
                              prop="sort">
                    <el-input-number v-model="form.sort"
                                     :step="1"></el-input-number>
                </el-form-item>
                <el-form-item label="内容"
                              prop="content">
                    <el-input v-model="form.content"
                              type="textarea"
                              placeholder="请输入内容"
                              :autosize="{minRows: 4, maxRows: 4}"
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer"
                 class="dialog-footer">
                <el-button type="primary"
                           @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listModuleResource,
    getModuleResource,
    delModuleResource,
    addModuleResource,
    updateModuleResource,
    exportModuleResource,
} from '@/api/system/moduleResource'
import { uploadFileUrl, baseUrl, ueditorUploadFileUrl } from '@/api/config'

export default {
    name: 'ModuleResource',
    data() {
        return {
            imageUrl: '',
            uploadFaceImgAction: uploadFileUrl,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 状态字典
            stateOptions: [],
            // 模块资源表格数据
            moduleResourceList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                moduleType: null,
                imageId: null,
                title: null,
                content: null,
                jumpUrl: null,
                jumpType: null,
                sort: null,
            },
            rules: {
                moduleType: [
                    {
                        required: true,
                        message: '请选择模块类型',
                        trigger: 'change',
                    },
                ],
                title: [
                    {
                        required: true,
                        message: '请输入标题',
                        trigger: 'blur',
                    },
                ],
            },
            // 表单参数
            form: {
                moduleType: undefined,
                imageId: null,
                title: undefined,
                jumpUrl: undefined,
                content: undefined,
                jumpType: '',
                sort: 0,
            },
        }
    },
    created() {
        this.getDicts('official_website_configure').then((response) => {
            this.stateOptions = response.data
        })
        this.getList()
    },
    methods: {
        // 状态字典翻译
        stateFormat(row, column) {
            return this.selectDictLabel(this.stateOptions, row.moduleType)
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = ''
            if (res.code === 200) {
                this.imageUrl = res.data.fileUrl
                this.form.imageId = res.data.id
            } else {
                this.$message.error(res.msg)
            }
        },
        beforeAvatarUpload(file) {
            console.log(file)
            const isJPG =
                file.type === 'image/jpeg' || file.type === 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG/PNG 格式!')
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!')
            }
            return isLt2M
        },
        /** 查询模块资源列表 */
        getList() {
            this.loading = true
            listModuleResource(this.queryParams).then((response) => {
                this.moduleResourceList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                moduleType: null,
                imageId: null,
                title: null,
                content: null,
                jumpUrl: null,
                jumpType: null,
                sort: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
            }
            this.imageUrl = ''
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加模块资源'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getModuleResource(id).then((response) => {
                this.form = response.data
                this.imageUrl = baseUrl(response.data.imageId)
                this.open = true
                this.title = '修改模块资源'
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.id != null) {
                        updateModuleResource(this.form).then((response) => {
                            this.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addModuleResource(this.form).then((response) => {
                            this.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$confirm(
                '是否确认删除模块资源编号为"' + ids + '"的数据项?',
                '警告',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(function () {
                    return delModuleResource(ids)
                })
                .then(() => {
                    this.getList()
                    this.msgSuccess('删除成功')
                })
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams
            this.$confirm('是否确认导出所有模块资源数据项?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(function () {
                    return exportModuleResource(queryParams)
                })
                .then((response) => {
                    this.download(response.msg)
                })
        },
    },
}
</script>

<style lang='scss'>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 300px;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 300px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 100%;
    height: 178px;
    display: block;
}
.el-table {
    .cell {
        max-height: 100px;
        img {
            width: 100%;
        }
    }
}
</style>
